# 导包
from urllib.parse import urlencode

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re

from meiduo_mall.settings.dev import logger
from utils.secret import SecretOauth
from .models import User

# 生成激活链接
def generate_verify_email_url(user):
    host_url = settings.EMAIL_ACTIVE_URL

    data_dict = {
        'user_id': user.id,
        "email": user.email
    }
    # 加密
    dumps_params = SecretOauth().dumps(data_dict)
    verify_url = settings.EMAIL_ACTIVE_URL + '?token=' + dumps_params
    return verify_url


# 封装
def get_user_by_account(account):
    try:
        if re.match('^1[345789]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        logger.error('用户对象不存在!')
        return None
    else:
        return user

# 继承类
class UsernameMobileAuthBackend(ModelBackend):
     def authenticate(self, request, username=None, password=None, **kwargs):
             # 校验多账号
             user = get_user_by_account(username)
             # 校验密码是否正确
             if user and user.check_password(password):
                return user

# 配置 dev
